<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websoket发送消息</title>
    <script src="/jquery-3.3.1.min.js"></script>
</head>
<body>
<p>【userId】：<div><input id="userId" name="userId" type="text" ></div>
<p>【toUserId】：<div><input id="toUserId" name="toUserId" type="text" ></div>
<p>【toUserId】：<div><input id="contentText" name="contentText" type="text" value="hello websocket"></div>
<p>【操作】：<div><button onclick="openSocket()">开启socket</button></div>
<p>【操作】：<div><button onclick="sendMessage()">发送消息</button></div>
发送的消息 <br>
<input type="text"  id="send" >
收到的消息 <br>
<input type="text"  id="rec" >
<script>
    var socket=null;//声明socket
    function openSocket() {

        if (typeof (socket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");

        } else {
            console.log("您的浏览器支持WebSocket");
            //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
            //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
            //var socketUrl="${request.contextPath}/im/"+$("#userId").val();
            var socketUrl = "http://localhost:8080/imserver/"+ $("#userId").val();
            socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
            console.log("连接地址"+socketUrl);
            if (socket != null) {
                socket.close();
                socket = null;
            }else {
                console.log("socke的地址问题");
            }
            socket = new WebSocket(socketUrl);
            //soket打开
            socket.onopen = function () {
                console.log("Soket打开");

            }
            socket.onclose = function () {
                console.log("Soket关闭");
            }
            socket.onerror = function () {
                console.log("Soket发生错误");
            }
            socket.onmessage = function (event) {//发送和接收消息
                console.log(event);
                console.log(event.data);

                console.log(event.data);
                $("#rec").val(event.data);//将获取的信息显示



            }

        }
    }
    function sendMessage() {//发送消息
        if(typeof(socket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else {
            console.log("您的浏览器支持WebSocket");
            var contentText=$("#contentText").val();
            console.log('{toUserId:"'+$("#toUserId").val()+'",contentText:"'+$("#contentText").val()+'"}');
              $("#send").val(contentText);
            socket.send('{toUserId:"'+$("#toUserId").val()+'",contentText:"'+$("#contentText").val()+'"}');
           $.ajax({
               url:"/push/"+$("#toUserId").val(),
               data:{
                   msg:contentText
               },success: function (data) {
                   console.log(data)


               }


           })


        }
    }

</script>
</body>
</html>